package com.bbs.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.bbs.common.consts.CommonConstant;
import com.bbs.common.utils.TokenUtils;
import com.bbs.common.vo.DataResult;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * LoginInterceptor
 *
 * @author yangjiajia
 * @createdAt 2024/4/1 17:37
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(DataResult.fail(999, "用户未登录")));
            return false;
        }

        Map<String, Object> payload = TokenUtils.parseJWT(token);
        if (null == payload) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(DataResult.fail(999, "用户未登录")));
            return false;
        }

        payload.forEach(request::setAttribute);

        return true;
    }
}
